package com.prpat;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

import de.uniba.wiai.lspi.chord.service.PropertiesLoader;

public class Starter 
{
	public static final String iface ;
	
	static
	{
		// read property file by invoking static method on ChordImpl
		PropertiesLoader.loadPropertyFile();
		iface = System.getProperty("com.prpat.Globals.interface");
	}
	
	public static void main(String[] args)
	{
		
		if(iface.equalsIgnoreCase("cmd"))
		{
			TaskAssistant.initializer();
			
			boolean run = true;
			int option = 0;
			
			while(run)
			{
				menu();
				option = input();
				if(option == 2)
					run = false;
				else if( !TaskAssistant.CONNECTED && option == 1 )
					TaskAssistant.CONNECTED = TaskAssistant.startChord();
				else if( TaskAssistant.CONNECTED && option == 1 )
					TaskAssistant.sendMessage();
			}
			TaskAssistant.ocExecuted("exit");
			TaskAssistant.suicider();
		}
		else if(iface.equalsIgnoreCase("gui"))
		{
			Starter gui = new Starter();
			gui.connecter();
		}
	}
	
	private static void menu()
	{
		System.out.println("----        Menu        ----");
		if(!TaskAssistant.CONNECTED)
		{
			System.out.println("1) Start Chord");
			System.out.println("2) Exit");
		}
		else
		{
			System.out.println("1) Send Hash");
			System.out.println("2) Exit");
		}
		System.out.println("--> ");
	}
	
	private static int input()
	{
		InputStreamReader isReader = new InputStreamReader(System.in);
		BufferedReader reader = new BufferedReader(isReader);
		while (true)
		{
			try 
		    {
				// Integer.parseInt turns a string into an int
		        return Integer.parseInt(reader.readLine());
		    } 
		    catch (NumberFormatException nfe) 
		    {
		    	// but it throws an exception if the String doesn't look like any integer it recognizes
		    	System.err.println("Starter, input, " + nfe.getMessage());
		        System.out.println("That's not a valid option! Try again.");
		    } 
		    catch (IOException e)
		    {
		    	System.err.println("Starter, input, " + e.getMessage());
		    	System.out.println("That's not a valid option! Try again.");
			}
		}
	}
	
	private void connecter() 
	{		
		TaskAssistant.connectFrame = new JFrame("Chord Chat");
		TaskAssistant.connectFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel mainPanel = new JPanel();
        
        TaskAssistant.display = new JTextArea(26, 50);
        TaskAssistant.display.setLineWrap(true);
        TaskAssistant.display.setWrapStyleWord(true);
        TaskAssistant.display.setEditable(false);
        
        JScrollPane qScroller = new JScrollPane(TaskAssistant.display);
        qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        
        JButton connectButton = new JButton("Connect to Chord Network");
        connectButton.addActionListener(new ConnectButtonListener());
        
        mainPanel.add(qScroller);
        mainPanel.add(connectButton);
        
        TaskAssistant.connectFrame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        TaskAssistant.connectFrame.setSize(650, 500);
        TaskAssistant.connectFrame.setVisible(true);
        
        TaskAssistant.initializer();
	}

	private class ConnectButtonListener implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent ev) 
		{
			TaskAssistant.CONNECTED = TaskAssistant.startChord();
			if(TaskAssistant.CONNECTED)
			{
				TaskAssistant.connectFrame.dispose();
				sender();
			}
			else
			{			
				TaskAssistant.display.append("Error while connecting to the network\n");
				TaskAssistant.display.append("Please try again\n");
			}
		}
	}
	
	private void sender()
	{
		TaskAssistant.dialogFrame = new JFrame("Chord Chat @" + TaskAssistant.BOOTSTRAP);
		TaskAssistant.dialogFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel mainPanel = new JPanel();
        
        TaskAssistant.display = new JTextArea(26, 50);
        TaskAssistant.display.setLineWrap(true);
        TaskAssistant.display.setWrapStyleWord(true);
        TaskAssistant.display.setEditable(false);
        
        JScrollPane qScroller = new JScrollPane(TaskAssistant.display);
        qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        
        TaskAssistant.input = new JTextField(30);
        JButton sendButton = new JButton("Send Hash");
        sendButton.addActionListener(new SendButtonListener());
        
        mainPanel.add(qScroller);
        mainPanel.add(TaskAssistant.input);
        mainPanel.add(sendButton);
        
        TaskAssistant.dialogFrame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        TaskAssistant.dialogFrame.setSize(650, 500);
        TaskAssistant.dialogFrame.setVisible(true);
	}

	public class SendButtonListener implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent ev) 
		{	
			String in = TaskAssistant.input.getText();
			if(in.equalsIgnoreCase("file") || in.length()<1)
				TaskAssistant.sendMessage();
			else
				TaskAssistant.sendMessage(in);
			
//			TaskAssistant.display.append(TaskAssistant.input.getText() + "\n");
			TaskAssistant.input.setText("");
			TaskAssistant.input.requestFocus();
		}
	}

}
